<?php session_start() ?>
<!DOCTYPE html>
<html>
<head>
	<meta charset="utf-8">
	<title>search properties</title>
	<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
	<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">
	<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
	<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js"></script>
</head>
<body>
	
<?php
require_once 'header.php';
require 'connect.php';

$status = '';
?>


<!-- This will take all city names from current DB and add them to 
 search list tags in html via PHP. After that, depending on selected city, related suburbs are going to be put from DB inside drop check list.
 So customer will only be able to choose from what data actualiy in DB.
 This prevents typos and unneccessery search requests. -->





<div id="search-wrapper">
	<div id="search-form" class='container'>
		<div class="row">
					<div id="card-header">
						<h1 id="form-se-head">PROPERTY SEARCH FORM</h1>
					</div>
					<div class="card-body">
						<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
							<div class="form-row">
								<div class="form-group col">
									<select class="form-control" id="city" name="city">
										<option>SELECT CITY</option>
										<!-- adding all distinct cities from DB to search list -->
										<?php 
										$result = mysqli_query($conn,"SELECT DISTINCT city from addresses ORDER BY city ASC");
										if ($result->num_rows > 0){
											while($row = mysqli_fetch_array($result)){ 
										?>
										<option value="<?php echo $row['city'];?>"><?php echo $row['city'];?></option>
										<?php
											}
										} else {$query_error = 'some error getting city data';}
										?>
									</select>
								</div>

								<div class="col">
									<!-- this dropdown populates from first one with 
											help of AJAX script above divs and suburb_list.php -->
									<div class="dropdown input-group">
									<button class="btn btn-secondary dropdown-toggle btn-block" type="button" 
									data-toggle="dropdown">
									SELECT SUBURB
									</button>
									<div class="dropdown-menu">
									<button class="dropdown-item" type="button" id="suburb">
									<option>no suburb detected</option>
									</button>
									</div>
									</div>
								</div>	

							</div>
							<div class=" form-row">
								<div class=" col">
									<select class="form-control" name='price'>
										<option>Price</option>
										<option value="150000">$150K+</option>
										<option value="300000">$300K+</option>
										<option value="600000">$600K+</option>
										<option value="1000000">$1M+</option>
									</select>
								</div>
								<div class=" col">
									<select class="form-control" name='bedrooms'>
										<option>Bedrooms</option>
										<option value="0">Any</option>
										<option value="1">1+</option>
										<option value="2">2+</option>
										<option value="3">3+</option>
									</select>
								</div>
							</div>

							<div class="form-group text-center">
									<input id="sub-btn-search" type="submit" name="submit" class="btn-max btn-size" value="Submit" id="submit_search">
							</div>
						</form>
					</div>
		</div>
	</div>
</div>

<div class="search-results">
<?php

if( isset($_POST['submit'])){
// print_r($_POST); /////displaying for debuging purposes only



	if( !empty($_POST['city'])){

		$city = $_POST['city'];

		$sql = "SELECT bedrooms, price, description, suburb, city, street_name, street_number,  properties.id FROM properties
		INNER JOIN addresses ON addresses.property_id = properties.id
		WHERE city = '".$city."'";

					// echo $sql, "<br>";/////displaying for debuging purposes only
					// echo	print_r($_POST['suburbs']);/////displaying for debuging purposes only
		// $current_user = $_SESSION['user_id'];

		if( !empty($_POST['suburbs'])){


			$suburbs_names = "";

			foreach($_POST['suburbs'] as $value){

				if (empty($suburbs_names)){

					$suburbs_names = "'".$value."'"; 
				}
				else{ $suburbs_names = $suburbs_names.", '.$value.'"; }

        }
        $sql = "SELECT bedrooms, price, description, suburb, city, street_name, street_number, properties.id FROM properties 
					INNER JOIN addresses ON addresses.property_id = properties.id
					WHERE addresses.suburb IN (".$suburbs_names.")";

					// echo  $sql, "<br>"; ////displaying for debuging purposes only
		}

		if(!($_POST['price'] === 'Price')){
			$price = $_POST['price'];
			$sql = $sql." AND price > ".$price;
		}
		if (!($_POST['bedrooms'] === 'Bedrooms')){
			$bedrooms = $_POST['bedrooms'];
			$sql = $sql." AND bedrooms > ".$bedrooms;
		}


		// echo $sql;/////displaying for debuging purposes only

		$result = mysqli_query($conn, $sql);
			 
			//echo print_r ($result);

		if (mysqli_num_rows($result) > 0){
			while($row = mysqli_fetch_assoc($result)){
				
				// echo print_r($row), "<br>";////displaying for debuging purposes only -->
				
				//getting photos urls or current property
				if(isset($_SESSION['user_id'])){

					$sql = "SELECT property_id, wishlists.user_id FROM wishlists WHERE property_id = $row[id] AND user_id = ".$_SESSION['user_id'];
					$result_wishlist = mysqli_query($conn, $sql);

					if (mysqli_num_rows($result_wishlist) ==  0 ) {
						$wishlist_state = "Add to Wishlist";
						$btn_color = "add-to-wishlist-btn";
					}
					else {
						$wishlist_state = "Remove from Wishlist";
						$btn_color = "add-to-wishlist-btn-toggle add-to-wishlist-btn";
					}

				}else {$display = 'd-none'; }
				
				$sql = "SELECT photo_url FROM photos WHERE property_id = $row[id]";
				$result_photos = mysqli_query($conn, $sql);

				if (mysqli_num_rows($result_photos) > 0){ ?>


				<div>
					<?php $current_property_photo_urls = mysqli_fetch_assoc($result_photos);
					// echo ($current_property_photo_urls['photo_url']);////displaying for debuging purposes only
					$photoUrl = $current_property_photo_urls['photo_url'];
					// echo $photoUrl;
					?>
				</div>
<section class="search-results-body">
	<div class="column one-half">
        <div class="col-group dis-card">
          <div class="img-container">
            <img src="<?php echo $photoUrl;?>" class="house-img" width="300px" height="200px">
          </div>
          <h2 class="house-title"><?php echo $row['street_number']. ' '.$row['street_name']. ', '.$row['suburb']. ', '.$row['city']  ?></h2>
          <div class="bedroom-wrapper">
		  	<span class="house-price"><?php echo '$'.number_format($row['price']); ?></span>
            <span class="bed-number"><?php echo $row['bedrooms'] ?></span>
            <img src="WebsiteImg/bed.png" class="bed-img">
          </div>
		  <p class="desc-text-cards"><?php echo $row['description'] ?></p>
		  <a class="<?php echo $btn_color.' '.$display;?> addtowishlist whishstate" onclick="AddWhish(<?php echo $row['id']; ?>)" data="<?php echo $row['id']; ?>"><?php echo $wishlist_state;?></a>
        </div>
      </div>
</section>


			<?php
				}
			}
		} else {$status = "City has to be selected.";}
	}
}
?>

<script type="text/javascript">
   $(document).ready(function(){
   	// City dependent ajax
   	$("#city").on("change",function(){
   	var city_selected = this.value;
    $.ajax({
		url: "suburb_list.php",
		type: "POST",
		cache:false,
		data:{ city_selected: city_selected },
  		success:function(result){
      	$("#suburb").html(result);
  		}
    });	
  });
});
</script>

<script type="text/javascript">
function AddWhish(id){
	var link_data = id;
	   console.log('Link_data:'+link_data);
       $.ajax({
          type: "POST",
          url: 'addtowishlist.php',
          cache:false,
          data: { link_data: link_data },
          	success:function(result){
				  console.log("AJ success"+result);
               if(result == 1)
               {
                   $('a[data="' + link_data + '"]').addClass("add-to-wishlist-btn-toggle").text("Remove from Wishlist");
               }
               else{
                   $('a[data="' + link_data + '"]').removeClass("add-to-wishlist-btn-toggle").text("Add to Wishlist");
               }
          },
		  error:function(result){
			console.log("AJ error");

		  }
       });   
}
</script>
</div>
</body>
</html>